<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }" :default-params="{ adCode: [], stage:'8' }" @submit="handleSeachTable">
      <t-col :span="3">
        <!-- <div style="margin-left: 100px;color: red;font-size: 12px;">在途客户为转设计至合同阶段</div> -->
        <t-form-item label="设计阶段" name="stage" >
          <t-select
            v-model:value="params.stage"
            :options="[...dictionaryStore.get('order_designer_stage'),{ label: '在途(转设计至合同阶段)', value: '8' }]"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="客户名称" name="name">
          <t-input v-model:value="params.name" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="手机号码" name="phone">
          <t-input v-model:value="params.phone" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="微信号码" name="wxCode">
          <t-input v-model:value="params.wxCode" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="归属城市" name="adCode">
          <t-cascader
            v-model:value="params.adCode"
            :options="city.tree"
            :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
            placeholder=""
            filterable
            clearable
            check-strictly
            value-type="full"
            @change="(value: any) => handleAdCodeChange(value, params)"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="来源渠道" name="channelSource">
          <t-select
            v-model:value="params.channelSource"
            :options="channelList"
            :keys="{ value: 'id', label: 'name' }"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="楼盘名称" name="propertyName">
          <t-select v-model:value="params.propertyName" clearable filterable placeholder="">
            <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
              {{ _.name }}
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="详细地址" name="address">
          <t-input v-model:value="params.address" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="房屋户型" name="houseType">
          <t-select
            v-model:value="params.houseType"
            :options="dictionaryStore.get('decoration_order_house_type')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="上报人" name="shangbaoId">
          <t-select
            v-model:value="params.shangbaoId"
            :options="reporteList"
            :keys="{ label: 'nickname', value: 'id' }"
            placeholder=""
            clearable
            filterable
            @clear="params.shangbaoId = null"
          />
        </t-form-item>
      </t-col>
      <!-- <t-col :span="3">
        <t-form-item label="设计部门" name="deptId">
          <t-cascader
            v-model:value="params.deptId"
            :options="simpleDeptTree"
            :keys="{ label: 'name', value: 'id' }"
            placeholder=""
            filterable
            clearable
            check-strictly
             @change="(val, ctx) => handleGetDesignerList(val)"
          />
        </t-form-item>
      </t-col> -->
      <t-col :span="3">
        <t-form-item label="客服" name="saleId">
          <t-cascader
            v-model:value="params.saleId"
            :options="saleTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
 
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="设计师" name="designerId">
          <t-cascader
            v-model:value="params.designerId"
            :options="designerTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
 
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="归属部门" name="deptId">
          <t-cascader
            v-model:value="params.deptId"
            :options="simpleDeptTree"
            :keys="{ label: 'name', value: 'id' }"
            placeholder=""
            filterable
            clearable
            check-strictly
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="归属公司" name="companyId">
          <t-select
          v-model:value="params.companyId"
          :options="companySimpleList"
          :keys="{ label: 'name', value: 'id' }"
          placeholder=""
          filterable
          clearable
        />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :on-before-set-data="handleTableSetData"
      :api="designOrderCRUD.page"
      :is-phone="false"
      column-controller-key="designOrderList"
      @request-success="handleTableRequestSuccess"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <TransferDesignData />
          <span v-if="hasData" style="margin-left: 10px;">
            <span v-for="stage in processedStages" :key="stage.value" class="stage-item">
        <span>{{ stage.label }}</span>
        <t-link theme="primary" v-if="stage.count > 0" @click="handleClick(stage.value, stage.ids)">
          {{ stage.count }}条；
        </t-link>
       
      </span>
          </span>
          <span v-if="hasData&&overdueStages.length>0">
            其中延期2次以上
            <span v-for="stage in overdueStages" :key="stage.value" class="stage-item">
        <span>{{ stage.label }}</span>
        <t-link theme="primary"  @click="handleClick(stage.value, stage.overdueIds)">
          {{ stage.overdueCount  }}条；
        </t-link>

      </span>
          </span>
        </div>
      </template>
      <template #stage="{ row }">
        {{ dictionaryStore.analysis('order_designer_stage', row.stage) }}
        <div>{{ dictionaryStore.analysis('engineering_stage', row.enginneringStage) }}</div>
      </template>
      <template #phone="{ row }">
        {{ maskPhone(row.phone) }}
        <span style="color: red;" v-if="['1','2','3','4','5'].includes(row.stage)">
          {{(dayjs().diff(dayjs(row.createTime).format('YYYY-MM-DD'), 'day'))}}天未签
        </span>
      </template>
      <template #customerLevel="{ row }">
        {{ dictionaryStore.analysis('decoration_order_customer_level', row.customerLevel) }}
      </template>
      <template #adCode="{ row }">
        {{ analysisCity(row) }}
      </template>
      <template #channelSource="{ row }">
        {{ channelList.find((item) => item.id.toString() === row.channelSource)?.name }}
      </template>
      <template #propertyName="{ row }">
        {{ propertyInfoList.find((item) => item.id === row.propertyName)?.name }}
        <span style="color: gray;">{{ row.address }}</span>
      </template>
      <template #houseType="{ row }">
        {{ dictionaryStore.analysis('decoration_order_house_type', row.houseType) }}
      </template>
      <template #reporterName="{ row }">
        {{ userStore.getUserNameById(row.creator) }}
      </template>
      <template #saleName="{ row }">
        {{ userStore.getUserNameById(row.saleId) }}
      </template>
      <template #designerName="{ row }">
        {{ userStore.getUserNameById(row.designerId) }}
      </template>
      <template #lastMessageTime="{ row }">
        {{ row.lastMessageTime&&dayjs(row.lastMessageTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #measureTime="{ row }">
        {{ row.measureTime && dayjs(row.measureTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #planeTime="{ row }">
        {{ row.planeTime && dayjs(row.planeTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #oneSeeTime="{ row }">
        {{ row.oneSeeTime && dayjs(row.oneSeeTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #twoSeeTime="{ row }">
        {{ row.twoSeeTime && dayjs(row.twoSeeTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <!-- 查看订单 -->
          <view-order :id="row.orderId" :operate-type="row.operateType" :design-order-id="row.id" />
          <!-- 转派设计师 -->
          <transfer-designer
            :ids="[row.orderId]"
            :company-id="row.companyId"
            :phone="row.phone"
            :designerId="row.designerId"
            @request-success="handleDialogRequestSuccess"
          />
          <!-- 申请废单 -->
          <apply-order-delete v-if="row.designerId === userStore.userInfo.id" :order-id="row.orderId" approve-type="4" @request-success="handleDialogRequestSuccess" />
          <!-- 重新发起合同 -->
          <renewal :order-id="row.orderId" v-if="row.stage==='6'||row.stage==='7'"/>
          <t-popconfirm content="确认要退回该项吗？" @confirm="handleReturn({ orderId: row.orderId })">
            <t-link v-permission="['system:order-designer:return-order']" theme="primary">退回</t-link>
          </t-popconfirm>
          <t-dropdown :options="options" @click="(data) => clickHandler(data, row)" :min-column-width="130">
            <t-link theme="primary" v-permission="['system:order-designer:delay-design']">更多</t-link>
          </t-dropdown>
        </t-space>
      </template>
    </custom-table>

    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData }"
      :api-map="{ update: delayeDesignInfo }"
      :header="header"
      :update-sucess-tip="header+'成功'"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item
        label="延期时间"
        name="extensionTime"
        :rules="[{ required: true, message: '请选择延期时间' }]"
      >
        <t-date-picker 
          allow-input
          v-model:value="formData.extensionTime"
          clearable
          placeholder="请选择延期时间"
          value-type="time-stamp"
          style="width: 100%"
          @change="
            (value) => {
              if (value) {
                value = dayjs(value).format('YYYY-MM-DD 23:59:59');
                
              }
              formData.extensionTime = value ? value : undefined;
            }
          "
        />
      </t-form-item>
      <t-form-item label="备注" name="extensionRemark" :rules="[{ required: true, message: '请输入备注' }]">
        <t-textarea v-model:value="formData.extensionRemark" placeholder="请输入备注" clearable />
      </t-form-item>
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'DesignOrder',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { computed, onMounted, onUpdated, Ref, ref, useTemplateRef, watch } from 'vue';

import { channelManageCRUD } from '@/api/config/common-config';
import { propertyManageCRUD } from '@/api/config/property';
import { designOrderCRUD, delayeDesignInfo, returnOrder } from '@/api/order/design';
import { getCompanyList, getSimpleDeptList } from '@/api/system/dept';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import ViewOrder from '@/pages/order/details/components/ViewOrder.vue';
import ApplyOrderDelete from '../single/components/ApplyOrderDelete.vue';
import Renewal from './components/Renewal.vue'
import TransferDesignData from './components/TransferDesignData.vue';
import TransferDesigner from '../basic/components/TransferDesigner.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import city from '@/utils/city';
import disposableParams from '@/utils/disposableParams';
import listToTree from '@/utils/listToTree';
import hasPermission from '@/utils/hasPermission';
import { getAllSimpleUserlist, getSimpleUserListByDeptId, getUserListByRoleCode, userCRUD } from '@/api/system/user';
import { useRoute } from 'vue-router';
import maskPhone from '@/utils/maskPhone'


// 用户仓库
const userStore = useUserStore();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 公司精简列表
const companySimpleList = ref([]);
// 处理获取公司精简列表
const handleGetCompanySimpleList = async () => {
  return getCompanyList().then((data) => {
    companySimpleList.value = data;
  });
};
handleGetCompanySimpleList();
// 渠道列表
const channelList = ref([]);
// 处理获取渠道列表
const handleGetChannelList = () => {
  const params = {
    pageSize: -1,
  };
  channelManageCRUD
    .page(params)
    .then((data) => {
      channelList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetChannelList();
// 精简部门树
const simpleDeptTree = ref([]);
// 处理获取精简部门树
const handleGetSimpleDeptTree = () => {
  getSimpleDeptList()
    .then((data) => {
      simpleDeptTree.value = listToTree(data);
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetSimpleDeptTree();
// 设计师列表
const designerList = ref([]);
// 客服
const saleList = ref([]);

// 获取用户通过rolecode
const fetchUsersByRole = async (roleCode: string, targetList: Ref<any[], any[]>) => {
  try {
    const data = await getUserListByRoleCode({ roleCode });
    data.forEach((item:any) => {
      item.name = item.nickname
      item.parentId = item.deptId
    });
    targetList.value = data;
  } catch (error) {
    console.error(`Error fetching users with role ${roleCode}:`, error);
    targetList.value = []; // Reset on error
  }
};

// 初始化所有用户
const initializeUserLists = () => {
  fetchUsersByRole('designer', designerList);
  fetchUsersByRole('sloe', saleList);
};

// Call initialization
initializeUserLists();
// 3. 合并部门和用户数据，生成树形结构
const generateCombinedTree = (deptTree: any[], userList: any[], userType: string) => {
  // 创建用户按部门ID分组的映射
  const userMap = new Map<number, any[]>();
  userList.forEach(user => {
    if (!userMap.has(user.deptId)) {
      userMap.set(user.deptId, []);
    }
    userMap.get(user.deptId).push({
      ...user,
      isUser: true,
      userType: userType
    });
  });

  // 递归处理部门树
  const processTree = (nodes: any[]): any[] => {
    return nodes.map(node => {
      const newNode = { ...node };
      
      // 处理子部门
      if (newNode.children) {
        newNode.children = processTree(newNode.children);
      } else {
        newNode.children = [];
      }
      
      // 添加当前部门的用户
      if (userMap.has(newNode.id)) {
        newNode.children.push(...userMap.get(newNode.id));
      }
      
      // 保留有用户或有子部门的节点
      if (newNode.children.length > 0) {
        return newNode;
      }
      
      return null;
    }).filter(Boolean);
  };

  return processTree(deptTree);
};
// 4. 计算属性：生成各种组合树
const designerTree = computed(() => {
  return generateCombinedTree(simpleDeptTree.value, designerList.value, 'designer');
});



const saleTree = computed(() => {
  return generateCombinedTree(simpleDeptTree.value, saleList.value, 'sloe');
});

// 上报人列表
const reporteList = ref([]);
// 处理获取上报人列表
const handleGetreporteList = () => {
  getAllSimpleUserlist()
    .then((data) => {
      reporteList.value = data;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetreporteList()
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'name', title: '客户名称 ', width: 80 },
  { colKey: 'phone', title: '手机号码', width: 110 },
  { colKey: 'propertyName', title: '楼盘名称', width: 200,  },
  { colKey: 'houseType', title: '房屋户型', width: 80 },
  { colKey: 'lastMessage', title: '最后记录内容', width: 200, ellipsis: true},
  { colKey: 'reporterName', title: '上报人', width: 100 },
  { colKey: 'saleName', title: '客服', width: 80 },
  { colKey: 'designerName', title: '设计师', width: 100 },
  { colKey: 'stage', title: '设计阶段', width: 80 },
  
  { colKey: 'customerLevel', title: '客户等级', width: 80 },
  
  { colKey: 'wxCode', title: '微信号码', width: 110 },
  { colKey: 'adCode', title: '归属城市', width: 190 },
  { colKey: 'channelSource', title: '来源渠道', width: 130 },
 
  // { colKey: 'address', title: '详细地址', width: 100 },
 
  { colKey: 'houseArea', title: '房屋面积(㎡)', width: 100 },


  { colKey: 'lastMessageTime', title: '最后记录时间', width: 160 },
  { colKey: 'measureTime', title: '量房更新时间', width: 160 },
  { colKey: 'planeTime', title: '方案更新时间', width: 160 },
  { colKey: 'oneSeeTime', title: '一见更新时间', width: 160 },
  { colKey: 'twoSeeTime', title: '二见更新时间', width: 160 },
  { colKey: 'createTime', title: '创建时间', width: 160 },
  { colKey: 'operation', title: '操作', width: 130, fixed: 'right' },
];
const handleSeachTable=(params:any) =>{
  disposableParams.set('to-do-tree-jump-params', {
    orderIds: '',
    operateType: '',
  });
  handleInitTable()
}
// 处理初始化表格
const handleInitTable = () => {
  // 待办树跳转参数
  const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
  if(customSearchRef.value.params.orderIds||toDoTreeJumpParams.orderIds) {
    customSearchRef.value.params.stage = ''
  }
  const params: Record<string, any> = {
    orderIds: toDoTreeJumpParams.orderIds,
    operateType: toDoTreeJumpParams.operateType,
    ...customSearchRef.value.params,
  };
  if (!params.adCode || !params.adCode.length) {
    delete params.province;
    delete params.city;
    delete params.area;
  }
  customTableRef.value.initTable(params);
  customSearchRef.value.params.orderIds =''
};
// 处理刷新表格
// const handleRefreshTable = () => {
//   customTableRef.value.refreshTable();
// };
// 处理表格请求成功
const handleTableRequestSuccess = ({ params, data }: Record<string, any>) => {
  data.forEach((item: Record<string, any>) => {
    item.operateType = params.operateType;
  });
};
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable()
})
// 处理退回
const handleReturn = (params: Record<string, any>) => {
  returnOrder(params)
    .then(() => {
      MessagePlugin.success('已发起退回审核');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理归属城市改变
const handleAdCodeChange = (value: string[], params: Record<string, any>) => {
  params.province = value[0] || '';
  params.city = value[1] || '';
  params.area = value[2] || '';
};
// 解析城市
const analysisCity = (row: Record<string, any>) => {
  let result = '';
  if (row.province) {
    result += city.list.find((item) => item.adcode === row.province).name;
  }
  if (row.city) {
    result += ` / ${city.list.find((item) => item.adcode === row.city).name}`;
  }
  if (row.area) {
    result += ` / ${city.list.find((item) => item.adcode === row.area).name}`;
  }
  return result;
};
// 根据权限过滤选项
// const filteredOptions = computed(() => {
//   return options.filter(option => hasPermission(option.permission));
// });
// 列表下拉
const options = [
  { content: '量房延期审核', value: 11, logType: 'measure_extension' },
  { content: '方案延期审核', value: 12, logType: 'plane_extension' },
  { content: '一见延期审核', value: 13, logType: 'oneSee_extension' },
  { content: '二见延期审核', value: 14, logType: 'twoSee_extension' },
  { content: '整装合同延期审核', value: 15, logType: 'contract_extension' },
];
const clickHandler = (data: any, row: any) => {
  handleOpenDialog('update',{ orderId: row.orderId, id:row.id,oaType: data.value, logType:data.logType },data.content)

};

// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>, head:string) => {
  customDialogRef.value.open(mode, params);
  header.value = head
};
// 对话框标题
const header = ref('')
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
const tableTotal = ref<Record<string,any>>({})
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  tableTotal.value = data.data
  return data
};
const hasData = computed(() => {
  return Object.keys(tableTotal.value).length > 0;
});
const processedStages = computed(() => {
  if(!hasData.value) return []
  return dictionaryStore.get('order_designer_stage').map(stage => {
        const ids = tableTotal.value[stage.value] ? tableTotal.value[stage.value].split(',') : [];
        const overdueIds = tableTotal.value[stage.value + 'oa'] ? tableTotal.value[stage.value + 'oa'].split(',') : [];
        
        return {
          ...stage,
          ids,
          count: ids.length,
          overdueIds,
          overdueCount: overdueIds.length
        };
      }).filter(stage => stage.count > 0);
});
// 所有延期数据
const overdueStages = computed(() => {
  if(!hasData.value) return []
 return dictionaryStore.get('order_designer_stage').map(stage => {
  const ids = tableTotal.value[stage.value] ? tableTotal.value[stage.value].split(',') : [];
    const overdueIds = tableTotal.value[stage.value + 'oa'] ? tableTotal.value[stage.value + 'oa'].split(',') : [];
    return {
      ...stage,
      overdueIds,
      ids,
      overdueCount: overdueIds.length
    };
  }).filter(stage => stage.overdueCount > 0);

});
// 点击条数
const handleClick= (stageValue:any,ids:any)=> {
  console.log(stageValue,ids,'ll');
  customSearchRef.value.params.orderIds = ids.toString()
  handleInitTable()
  console.log(processedStages.value,'22');
  

}
</script>
<style scoped>
.stage-item {
  margin-right: 6px;
}
</style>
